module.exports = function ($scope, $state, $resource, $modal, toaster){

	$scope.search = function (pageNo){
		var para = {
			'pageNo': pageNo || $scope.currentPage,
			'pageSize': $scope.itemsPerPage,
			'name': $scope.searchform.name,
			'type': $scope.searchform.type
		}
		$resource('/api/as/puc/citydiscount/getDiscountList', {}, {}).save(para, function(res){
			if(res.errcode === 0){
				$scope.list = res.data.results;
				$scope.totalItems = res.data.totalRecord;
				$scope.currentPage = pageNo;
			}else{
				toaster.error({title: '', body: res.errmsg});
			}
		});
	}

	init();
    //初始化列表
    function init(){
		$scope.currentPage = 1;			//当前页码
		$scope.itemsPerPage = 10;		//每页显示几条
		$scope.searchform = {};
		$scope.discount_type = [
			{'name': '全部', 'value': ''},
			{'name': '打折优惠', 'value': '1'},
			{'name': '减价优惠', 'value': '2'}
		];
		$scope.search(1);
	};

	//删除优惠信息
	$scope.delete = function (index){
		if(confirm('确认删除优惠信息吗？') == true){
			$resource('/api/as/puc/citydiscount/deleteDiscount', {}, {}).save({'id': $scope.list[index].id}, function(res){
				if(res.errcode === 0){
					toaster.success({title: '', body: '删除成功'});
					$scope.list.splice(index,1);
				}else{
					toaster.error({title: '', body: res.errmsg});
				}
			});
		}
	};

	$scope.setDiscount = function(item) {
		var modalInstance = $modal.open({
			template: require('../views/setDiscount.html'),
			controller: 'setDiscount',
			size: 'lg',
			resolve: {
				item : function () {
					return item;
				},
				flag : function () {
					return true;
				}
			}
		});
		//关闭模态框刷新页面
		modalInstance.result.then(function(result) {
			if(result.id){
				item.name = result.name;
				item.verification_code = result.verification_code;
				item.discount_proportion = result.discount_proportion;
				item.discount_price = result.discount_price;
				item.discount_type = result.discount_type;
				item.discount_limit_type = result.discount_limit_type;
				item.verification_type = result.verification_type;
				item.verification_id = result.verification_id;
			} else {
				$scope.search(1);
			}
		});
	};

	//添加优惠产品
	$scope.addProduct = function(info){
		var a = info.discount_type==1 ? info.discount_proportion : info.discount_price;
		var para = {
			'discount': info.discount_type + '_' + a + '_' + info.name,
			'id': info.id
		}
		$state.go('app.discountInfo', para);
	};

};